package cn.aws360.boot.data.api.factory;

import cn.aws360.boot.data.api.pojo.properties.DruidProperties;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;

import javax.servlet.*;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author junnan
 */
@Slf4j
public class DruidFactory {

    public static DruidDataSource createDruidDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = new DruidDataSource();

        // 数据库连接相关设置
        dataSource.setUrl(druidProperties.getUrl());
        dataSource.setUsername(druidProperties.getUsername());
        dataSource.setPassword(druidProperties.getPassword());

        // 连接驱动
        if (StrUtil.isNotBlank(druidProperties.getDriverClassName())) {
            dataSource.setDriverClassName(druidProperties.getDriverClassName());
        }

        // 定义初始连接数
        dataSource.setInitialSize(druidProperties.getInitialSize());

        // 定义最大连接数
        dataSource.setMaxActive(druidProperties.getMaxActive());

        // 最小空闲
        dataSource.setMinIdle(druidProperties.getMinIdle());

        // 最长等待时间
        dataSource.setMaxWait(druidProperties.getMaxWait());

        // 是否缓存 preparedStatement
        dataSource.setPoolPreparedStatements(druidProperties.getPoolPreparedStatements());

        // PSCache 数量
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(druidProperties.getMaxPoolPreparedStatementPerConnectionSize());

        // 检测连接是否有效的 sql
        dataSource.setValidationQuery(druidProperties.getValidationQuery());

        // 检测连接是否有效的超时时间
        dataSource.setValidationQueryTimeout(druidProperties.getValidationQueryTimeout());

        // 连接获取时候的检测
        dataSource.setTestOnBorrow(druidProperties.getTestOnBorrow());
        dataSource.setTestOnReturn(druidProperties.getTestOnReturn());
        dataSource.setTestWhileIdle(druidProperties.getTestWhileIdle());

        // 连接池中的 minIdle 数量以内的连接
        dataSource.setKeepAlive(druidProperties.getKeepAlive());

        // 检测的间隔时间
        dataSource.setTimeBetweenEvictionRunsMillis(druidProperties.getTimeBetweenEvictionRunsMillis());

        // 保持空闲的连接多久以后会被清除
        dataSource.setMinEvictableIdleTimeMillis(druidProperties.getMinEvictableIdleTimeMillis());

        try {
            dataSource.setFilters(druidProperties.getFilters());
        } catch (SQLException e) {
            log.error("数据库连接池初始化异常：druidProperties: {}", druidProperties, e);
        }
        return dataSource;
    }

    public static ServletRegistrationBean<StatViewServlet> createServletRegistrationBean(DruidProperties druidProperties) {
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>();
        registrationBean.setServlet(new StatViewServlet());
        registrationBean.addUrlMappings(druidProperties.getUrlMappings());
        registrationBean.addInitParameter("resetEnable", druidProperties.getResetEnable());
        registrationBean.addInitParameter("loginUsername", druidProperties.getAdminLoginUsername());
        registrationBean.addInitParameter("loginPassword", druidProperties.getAdminLoginPassword());
        return registrationBean;
    }

    public static FilterRegistrationBean<WebStatFilter> createFilterRegistrationBean(DruidProperties druidProperties) {
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>();
        WebStatFilter filter = new WebStatFilter();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(druidProperties.getAdminWebStatFilterUrlPattern());
        registrationBean.addInitParameter("exclusions", druidProperties.getAdminWebStatFilterExclusions());
        registrationBean.addInitParameter("sessionStatEnable", druidProperties.getAdminWebStatFilterSessionStatEnable());
        registrationBean.addInitParameter("sessionStatMaxCount", druidProperties.getAdminWebStatFilterSessionStatMaxCount());
        String sessionName = druidProperties.getAdminWebStatFilterPrincipalSessionName();
        if (StrUtil.isNotBlank(sessionName)) {
            registrationBean.addInitParameter("principalSessionName", sessionName);
        }
        String cookieName = druidProperties.getAdminWebStatFilterPrincipalCookieName();
        if (StrUtil.isNotBlank(cookieName)) {
            registrationBean.addInitParameter("principalCookieName", cookieName);
        }
        registrationBean.addInitParameter("profileEnable", druidProperties.getAdminWebStatFilterProfileEnable());
        return registrationBean;
    }

    @SuppressWarnings("ALL")
    public static FilterRegistrationBean removeDruidAdFilterRegistrationBean(DruidProperties druidProperties) {
        String commonJsPattern = druidProperties.getUrlMappings().replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        Filter filter = new Filter() {
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                chain.doFilter(request, response);
                response.resetBuffer();
                String text = Utils.readFromResource(filePath);
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }

            @Override
            public void destroy() {
            }
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }

}
